<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/store'
import { useDebounceFn } from '@vueuse/core'
import { showToast } from 'vant'
import { useWaitUserLoadFn } from '@/hooks'

import { fetchNewbieTask, fetchNewbieRewards } from '@/api/task.js'
import { uploadEvent } from '@/api/upload.js'

import { useLoadAdxReward } from '@/utils/adx.js'
import { newbieTaskReward } from '/public/adConfig.js'

import TaskCard from '@/components/taskCard/taskCard.vue'
import BiPopup from '@/components/biPopup/index.vue'
import { event } from 'vue-gtag'

const userStore = useUserStore()

const newbieTask = ref({})
function handleFetchNewbieTask() {
    fetchNewbieTask(userStore.uuid).then(res => {
        newbieTask.value = res.data.data
        userStore.$patch({
            finishNewbieTask: newbieTask.value.every(item => item.finished)
        })
    })
}
useWaitUserLoadFn(handleFetchNewbieTask)

async function handleUploadADId() {
    try {
        await uploadEvent({
            device: userStore.uuid,
            reportId: newbieTaskReward,
            reportType: 2,
        })
        
        handleFetchNewbieTask()
    } catch (error) {
        console.error(error)
    }
}

const { init } = useLoadAdxReward(
    '',
    {
        emptyCallback: () => {
            showToast('Ad is loading. Please try again later.')
        },
        endCallback: () => { 
            handleUploadADId()
        }
    }
)
const handleWatchAds = useDebounceFn(() => {
    init()
}, 1000)

const Task = {
    5: {
        name: 'Log in',
        icon: 'login.png',
        hideCount: true,
        fn: () => { android.jumpToLogin() }
    },
    6: {
        name: 'Watch 5 Ads',
        icon: 'watch.png',
        hideCount: false,
        fn: () => { handleWatchAds() }
    }
}

function filterName(id) {
    return Task[id].name
}

function filterIcon(id) {
    return Task[id].icon
}

function filterCount(id) {
    return Task[id].hideCount
}

function filterStatus(task) {
    let completed = false

    if (task.taskId == 1) {
        completed = task.login // 已完成
    }

    if (task.taskId == 2) {
        completed = task.adCount >= 5 // 已完成
    }

    if (completed && !task.finished) {
        return 1
    }

    if (task.finished) {
        return 2
    }

    return 0
}

function filterFinishCount(task) {
    if (task.taskId == 2) {
        return task.adCount > 5 ? 5 : task.adCount
    }
}

const currentTask = ref({})
function handleTaskFn(task) {
    const status = filterStatus(task)
    if (status === 0) {
        Task[task.taskId].fn()
    }

    if (status === 1) {
        currentTask.value = task // 供奖励弹窗使用
        handleOpenRewardPopup()
    }
}

const rewardPopup = ref(false)
function handleOpenRewardPopup() {
    rewardPopup.value = true
}
function handleCloseRewardPopup() {
    rewardPopup.value = false
}
const handelGetRewrad = useDebounceFn(async () => {
    try {
        await fetchNewbieRewards({
            device: userStore.uuid,
            taskId: currentTask.value.taskId
        })
        showToast('Reward Claimed Successfully')
        handleFetchNewbieTask() // 领取成功刷新新手任务列表
        handleCloseRewardPopup()
        userStore.handleGetUserInfo()
    } catch (error) {
        console.error(error)
    }
    event(filterName(currentTask.value.taskId), {
        userId: userStore.uuid
    })
}, 500)

const popupProps = computed(() => {
    return {
        type: 'normal',
        buttonText: 'Get it',
        rewardsType: 'coin',
        rewardsNum: 100
    }
})
</script>

<template>
    <div class="box">
        <div class="box-title">
            <span class="box-title-main">Newbie Benefits</span>
            <span class="box-title-sub">
                (Can be withdrawn directly <span class="box-title-sub-inset">$1.0</span>)
            </span>
        </div>
        <div class="box-content">
            <TaskCard v-for="task in newbieTask" :key="task.taskId" :name="filterName(task.taskId)"
                :icon="filterIcon(task.taskId)" type="coin" :num="100" :hide-count="filterCount(task.taskId)"
                :status="filterStatus(task)" :finish-count="filterFinishCount(task)" :total-count="5"
                @btn-click="handleTaskFn(task)" />
        </div>
    </div>

    <BiPopup v-model:show="rewardPopup" v-bind="popupProps" @click="handelGetRewrad">
    </BiPopup>
</template>

<style scoped lang="scss">
.box {
    @extend %box;

    &-title {
        @extend %box-title;

        &-main {
            @extend %box-title-main;
        }

        &-sub {
            @extend %box-title-sub;

            &-inset {
                color: var(--task-color);
            }
        }
    }

    &-content {
        @extend %box-content;
    }
}
</style>